package com.panshi.config;

import com.panshi.api.SystemUserApi;
import com.panshi.po.SystemUserPo;
import com.panshi.vo.SystemUserNameQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class SysUserRealm extends AuthenticatingRealm {

    @Autowired
    SystemUserApi systemUserApi;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到用户密码token凭证
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)token;
        //获得登录用户名,密码
        String userName=usernamePasswordToken.getUsername();

        log.info("登录授权,username={}",userName);

        //根据用户名查询用户对象
        SystemUserNameQueryVo systemUserNameQueryVo=new SystemUserNameQueryVo();

        systemUserNameQueryVo.setUsername(userName);

        SystemUserPo systemUserPo=systemUserApi.queryName(systemUserNameQueryVo).getData();

        //如果等于null,说明用户不存在。
        //问题如何返回用户提示不存在呢？
        if(systemUserPo==null) {
            //通过抛出异常来解决提示错误信息
            throw new UnknownAccountException("用户不存在=".concat(userName));
        }
        //如果账号状态是禁用状态
        if(new Integer(0).equals(systemUserPo.getState())){
            throw new DisabledAccountException("用户被禁用=".concat(userName));
        }

        //账号正常，校验登录密码
        //第一个参数，存返回用户对象,第二个参数存密码，第三个登录用户名
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(systemUserPo, systemUserPo.getPassword(), systemUserPo.getUsername());

        //返回登录授权信息，shiro会自动校验转入的密码与数据库返回的密码是否一致，如果一致，代表登录成功
        return simpleAuthenticationInfo;
    }
}
